//
//  BiometricSetupView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import Foundation
import SwiftUI
import UIKit

struct BiometricSetupView: View {
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) private var dismiss
    
    @State private var showingAlert = false
    @State private var alertMessage = ""
    @State private var isEnabling = false
    @State private var isSetupComplete = false
    
    var onBiometricEnabled: (() -> Void)? = nil
    var onManualClose: (() -> Void)? = nil
    
    var biometricType: String {
        dataManager.getBiometricType()
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                Color(.systemGroupedBackground)
                    .ignoresSafeArea()
                
                VStack(spacing: 30) {
                    Spacer()
                    
                    // 图标
                    Image(systemName: biometricType == "Face ID" ? "faceid" : "touchid")
                        .font(.system(size: 80))
                        .foregroundColor(.orange)
                    
                    // 标题和描述
                    VStack(spacing: 16) {
                        Text("启用\(biometricType)登录")
                            .font(.title)
                            .fontWeight(.bold)
                            .multilineTextAlignment(.center)
                        
                        Text("使用\(biometricType)快速安全地登录您的账户，无需每次输入验证码。")
                            .font(.body)
                            .foregroundColor(.secondary)
                            .multilineTextAlignment(.center)
                            .padding(.horizontal, 20)
                    }
                    
                    // 功能特点
                    VStack(spacing: 16) {
                        FeatureRow(icon: "bolt.fill", title: "快速登录", description: "一秒完成身份验证")
                        FeatureRow(icon: "lock.shield.fill", title: "安全可靠", description: "生物特征本地存储，更安全")
                        FeatureRow(icon: "person.fill.checkmark", title: "便捷体验", description: "无需记忆密码或验证码")
                    }
                    .padding(.horizontal, 20)
                    
                    Spacer()
                    
                    // 按钮区域
                    VStack(spacing: 12) {
                        if !isSetupComplete {
                            Button(action: {
                                enableBiometricLogin()
                            }) {
                                HStack {
                                    if isEnabling {
                                        ProgressView()
                                            .progressViewStyle(CircularProgressViewStyle(tint: .white))
                                            .scaleEffect(0.8)
                                    } else {
                                        Image(systemName: biometricType == "Face ID" ? "faceid" : "touchid")
                                    }
                                    
                                    Text(isEnabling ? "设置中..." : "启用\(biometricType)")
                                        .fontWeight(.semibold)
                                }
                                .foregroundColor(.white)
                                .frame(maxWidth: .infinity)
                                .padding()
                                .background(Color.orange)
                                .cornerRadius(12)
                            }
                            .disabled(isEnabling)
                        } else {
                            // 设置完成后显示成功状态
                            HStack {
                                Image(systemName: "checkmark.circle.fill")
                                    .foregroundColor(.green)
                                Text("\(biometricType)已成功启用")
                                    .fontWeight(.semibold)
                                    .foregroundColor(.green)
                            }
                            .frame(maxWidth: .infinity)
                            .padding()
                            .background(Color.green.opacity(0.1))
                            .cornerRadius(12)
                        }
                        
                        Button(isSetupComplete ? "完成设置" : "稍后设置") {
                            if isSetupComplete {
                                if AppConfig.enableDebugLogging {
                                    print("[DEBUG] BiometricSetupView: 用户点击完成设置按钮")
                                }
                                // 用户手动完成设置，调用成功回调
                                dismiss()
                                onBiometricEnabled?()
                            } else {
                                if AppConfig.enableDebugLogging {
                                    print("[DEBUG] BiometricSetupView: 用户点击稍后设置按钮")
                                }
                                // 用户选择稍后设置
                                dismiss()
                                onManualClose?()
                            }
                        }
                        .foregroundColor(isSetupComplete ? .orange : .secondary)
                        .fontWeight(isSetupComplete ? .semibold : .regular)
                        .padding(.vertical, 8)
                    }
                    .padding(.horizontal, 20)
                    .padding(.bottom, 30)
                }
            }
            .navigationTitle("")
            .navigationBarHidden(true)
        }
        .alert("提示", isPresented: $showingAlert) {
            Button("确定", role: .cancel) {
                if alertMessage.contains("成功") && AppConfig.biometricSetupAutoClose {
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] BiometricSetupView: 自动关闭模式，调用成功回调")
                    }
                    dismiss()
                    onBiometricEnabled?()
                } else {
                    // 成功但不自动关闭时，或者失败时，不调用onBiometricEnabled
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] BiometricSetupView: 非自动关闭模式或失败，不调用回调")
                    }
                }
            }
        } message: {
            Text(alertMessage)
        }
    }
    
    private func enableBiometricLogin() {
        if AppConfig.enableDebugLogging {
            print("[DEBUG] BiometricSetupView: 开始生物识别验证")
        }
        
        // 首先检查生物识别是否可用
        guard dataManager.isBiometricAvailable() else {
            if AppConfig.enableDebugLogging {
                print("[DEBUG] BiometricSetupView: 生物识别功能不可用")
            }
            alertMessage = dataManager.currentLanguage == "zh" ? "生物识别功能不可用" : "Biometric authentication not available"
            showingAlert = true
            return
        }
        
        isEnabling = true
        
        // 使用DataManager的authenticateWithBiometrics方法，它已经包含了正确的权限请求
        dataManager.authenticateWithBiometrics { success, error in
            
            DispatchQueue.main.async {
                self.isEnabling = false
                
                if AppConfig.enableDebugLogging {
                    print("[DEBUG] BiometricSetupView: 生物识别验证结果 - 成功: \(success), 错误: \(error ?? "无")")
                }
                
                if success {
                    self.dataManager.enableBiometricLogin()
                    
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] BiometricSetupView: 生物识别登录已启用，直接完成设置")
                    }
                    
                    // 生物识别验证成功后直接完成设置，不需要额外步骤
                    self.dismiss()
                    self.onBiometricEnabled?()
                } else {
                    let errorMsg = error ?? (self.dataManager.currentLanguage == "zh" ? "启用失败，请稍后重试" : "Setup failed, please try again later")
                    self.alertMessage = errorMsg
                    self.showingAlert = true
                }
            }
        }
    }
}

struct FeatureRow: View {
    let icon: String
    let title: String
    let description: String
    
    var body: some View {
        HStack(spacing: 16) {
            Image(systemName: icon)
                .font(.title2)
                .foregroundColor(.orange)
                .frame(width: 24)
            
            VStack(alignment: .leading, spacing: 4) {
                Text(title)
                    .font(.headline)
                    .foregroundColor(.primary)
                
                Text(description)
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }
            
            Spacer()
        }
        .padding(.vertical, 4)
    }
}

#Preview {
    BiometricSetupView()
        .environmentObject(DataManager.shared)
}